route.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { NextRequest, NextResponse } from 'next/server';
  2. import { ResultDto } from '@/types/response/common';
  3. import { fetchJson } from '@/lib/utils/server';
  4. function buildEndpoint(path?: string[]): string {
  5. const suffix = (path ?? []).join('/');
  6. return suffix ? `/api/feed/${suffix}` : '/api/feed';
  7. }
  8. async function forwardWithBody(request: NextRequest, endpoint: string, method: 'POST' | 'PUT'): Promise<ResultDto> {
  9. const contentType = request.headers.get('content-type') || '';
  10. if (contentType.includes('multipart/form-data')) {
  11. const form = await request.formData();
  12. return await fetchJson(endpoint, { method, body: form });
  13. }
  14. if (contentType.includes('application/json')) {
  15. const text = await request.text();
  16. return await fetchJson(endpoint, {
  17. method,
  18. body: text || undefined,
  19. headers: { 'Content-Type': 'application/json' }
  20. });
  21. }
  22. return await fetchJson(endpoint, {
  23. method,
  24. body: await request.arrayBuffer(),
  25. headers: contentType ? { 'Content-Type': contentType } : undefined
  26. });
  27. }
  28. export async function GET(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  29. const { path } = await params;
  30. const endpoint = buildEndpoint(path);
  31. const url = new URL(request.url);
  32. const res: ResultDto = await fetchJson(`${endpoint}${url.search}`, { method: 'GET' });
  33. return NextResponse.json(res);
  34. }
  35. export async function POST(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
  36. const { path } = await params;
  37. const endpoint = buildEndpoint(path);
  38. const res = await forwardWithBody(request, endpoint, 'POST');
  39. return NextResponse.json(res);
  40. }